# coding=utf-8
from decimal import Decimal

from django.db.models import F, Sum

from sutras import enums, models


def calculate_order_price(user_transcription, print_num):
    """
    计算印刷订单价格

    参数：
        user_transcription: 用户抄写对象
        print_num: 印刷数
    返回：
        {
            "total_price": Decimal("1.23"),  # 订单总价格
            "total_should_pay": Decimal("1.23"), # 订单需付金额
        }
    """
    # 计算单价
    unit_price = Decimal("0.00")

    layout = user_transcription.user_layout
    unit_price += layout.typeset.price
    unit_price += layout.material.price
    unit_price += layout.bind.price
    unit_price += layout.font_color.price

    unit_price += user_transcription.sutra_edition.print_price

    total_price = unit_price * print_num
    total_should_pay = total_price
    return {
        "total_price": total_price,
        "total_should_pay": total_should_pay,
    }


def finish_pay(order_id):
    rows = models.PrintOrder.objects.filter(
        serial_num=order_id,
        status=enums.PrintOrderStatus.unpaied).update(
            status=enums.PrintOrderStatus.paied,
            pay_status=enums.PrintOrderStatus.paied)
    if not rows:
        return False

    order = models.PrintOrder.objects.filter(
        serial_num=order_id).first()
    user = order.user
    user_level = models.UserLevelInfo.objects.get(user=user)

    print_num = models.PrintOrderDetail.objects.filter(
        print_order=order).aggregate(Sum("print_num"))["print_num__sum"]
    if print_num is None:
        print_num = 0

    # 更新用户果业
    user_level.print_book_num = F("print_book_num") + print_num
    user_level.total_cost = F("total_cost") + order.total_price
    user_level.save()

    return True
